import React, { Component } from "react";
import {
  Button,
  DatePicker,
  Input,
  Table,
  Divider,
  Popconfirm,
  Badge,
  message,
} from "antd";
import { connect } from "dva";
import moment from "moment";
import { Link } from "dva/router";
import tableFilter from "../../../components/tableFilter";
import styles from "./SupervisoryManager.less";
import { getChannelText } from "../../channelType";

const { Search } = Input;
const { RangePicker } = DatePicker;
const monitorType = ["", "消息源", "渠道名称", "渠道类型", "智能推送"];
@connect(({ supervisoryModel, channelDictionaryModel }) => ({
  supervisoryModelData: supervisoryModel,
  channelDictionaryModel,
}))
@tableFilter
class SupervisoryManager extends Component {
  state = {
    loading: true, // 页面是否在加载状态
    useStatus: "", // 表示状态 0为未提交 1为已提交（非必填）
    monitorName: "", // 监控名称（非必填）
    orderByTime: "desc", // 根据创建时间排序 desc/asc （非必填）
    startTime: "", // 开始时间（非必填）
    endTime: "", // 结束时间（非必填）
    pageNum: 1,
    pageSize: 10,
    supervisoryList: [], // 监控列表
    listTotal: 0, // 列表总数
  };

  componentDidMount() {
    const { dispatch } = this.props;
    this.filterFun();
    dispatch({
      type: "channelDictionaryModel/channelsTypes",
      payload: {},
    });
  }

  renderState = (status) => (
    <Badge
      status={status === "1" ? "success" : "error"}
      text={status === "1" ? "启用" : "停用"}
    />
  );

  renderType = (text) => {
    const { channelDictionaryModel } = this.props;
    const { channelsTypesData = [] } = channelDictionaryModel;
    return <span>{getChannelText(channelsTypesData, text)}</span>;
  };

  dateChange = (e) => {
    if (e && e.length > 0) {
      this.setState(
        {
          startTime: e[0].format("YYYY-MM-DD"),
          endTime: e[1].format("YYYY-MM-DD"),
          pageNum: 1,
        },
        () => {
          this.filterFun();
        }
      );
    } else {
      this.setState(
        {
          startTime: "",
          endTime: "",
          pageNum: 1,
        },
        () => {
          this.filterFun();
        }
      );
    }
  };

  handleTableChange = (e, filters, sorter) => {
    const { current, pageSize } = e;
    const { ownerDept, auditStatus, pushChannelType } = this.state;
    this.setState(
      {
        pageNum:
          (filters.ownerDeptName && filters.ownerDeptName !== ownerDept) ||
          (filters.auditStatus && filters.auditStatus !== auditStatus) ||
          (filters.pushChannelType &&
            filters.pushChannelType !== pushChannelType)
            ? 1
            : current,
        pageSize,
        orderByTime: sorter.order && sorter.order === "ascend" ? "asc" : "desc",
        useStatus: filters.useStatus ? filters.useStatus[0] : "",
      },
      () => {
        this.filterFun();
      }
    );
  };

  handleSearch = (e) => {
    this.setState(
      {
        monitorName: e,
        pageNum: 1,
      },
      () => {
        this.filterFun();
      }
    );
  };

  clearChange = (e) => {
    if (e.target.value !== "") return;
    this.setState(
      {
        monitorName: "",
        pageNum: 1,
      },
      () => {
        this.filterFun();
      }
    );
  };

  filterFun = () => {
    const {
      // loading,
      useStatus,
      monitorName,
      orderByTime,
      startTime,
      endTime,
      pageNum,
      pageSize,
    } = this.state;
    const { dispatch } = this.props;
    this.setState({
      loading: true,
    });
    dispatch({
      type: "supervisoryModel/supervisoryList",
      payload: {
        useStatus,
        monitorName,
        orderByTime,
        startTime,
        endTime,
        pageNum,
        pageSize,
      },
    }).then((res = {}) => {
      this.setState({
        supervisoryList: res.datas,
        loading: false,
        listTotal: res.totalCount,
      });
    });
  };

  startconfirm = (msgSourceId) => {
    const { dispatch } = this.props;
    dispatch({
      type: "supervisoryList/putOffline",
      payload: { msgSourceId, auditStatus: 2 },
    }).then(() => {
      const { offLineErr, offLineErrMsg } = this.props.messageData;
      if (offLineErr === 0) {
        message.success("发布成功");
        this.filterFun();
      } else {
        message.error(`发布失败，${offLineErrMsg}`);
      }
    });
  };

  endconfirm = (msgSourceId) => {
    const { dispatch } = this.props;
    dispatch({
      type: "supervisoryList/putOffline",
      payload: { msgSourceId, auditStatus: 1 },
    }).then(() => {
      const { offLineErr, offLineErrMsg } = this.props.messageData;
      if (offLineErr === 0) {
        message.success("下线成功");
        this.filterFun();
      } else {
        message.error(`下线失败，${offLineErrMsg}`);
      }
    });
  };

  deleteconfirm = (monitorId) => {
    const { dispatch } = this.props;
    dispatch({
      type: "supervisoryModel/delSupervisory",
      payload: { monitorId },
    }).then((res = {}) => {
      if (res.errCode === 0) {
        message.success("删除成功");
        this.filterFun();
      } else {
        message.error(`删除失败, ${res.msg}`);
      }
    });
  };

  changeStatus = (record) => {
    const { dispatch } = this.props;
    dispatch({
      type: "supervisoryModel/updateStatus",
      payload: {
        monitorId: record.monitorId,
        useStatus: record.useStatus === "1" ? "0" : "1",
      },
    }).then((res = {}) => {
      if (res.errCode === 0) {
        message.success(record.useStatus === "1" ? "停用成功" : "启用成功");
        this.filterFun();
      } else {
        message.error(`操作失败, ${res.msg}`);
      }
    });
  };

  render() {
    const { pageNum, loading, supervisoryList, listTotal } = this.state;

    const columns = [
      {
        title: "监控名称",
        dataIndex: "monitorName",
        key: "monitorName",
        width: 100,
        render: (text) => (
          <span
            title={text}
            style={{
              maxWidth: 180,
              textOverflow: "ellipsis",
              display: "block",
              whiteSpace: "nowrap",
              overflow: "hidden",
            }}
          >
            {text}
          </span>
        ),
      },
      {
        title: "监控类型",
        dataIndex: "monitorType",
        key: "monitorType",
        width: 50,
        render: (text) => monitorType[text],
      },

      {
        title: "告警渠道类型",
        dataIndex: "channelType",
        key: "channelType",
        width: 70,
        render: (text) => (text ? this.renderType(text) : "--"),
      },
      {
        title: "告警渠道名称",
        dataIndex: "reportChannelName",
        key: "reportChannelName",
        width: 100,
        render: (text) => <span title={text}>{text}</span>,
      },
      {
        title: "告警目标",
        dataIndex: "reporter",
        key: "reporter",
        width: 100,
        render: (text) => {
          const temp =
            text && text.length > 0
              ? text.map((item) => item.name).join(", ")
              : "---";
          return <span title={temp}>{temp}</span>;
        },
      },
      {
        title: "状态",
        dataIndex: "useStatus",
        key: "useStatus",
        render: (text) => this.renderState(text),
        filterMultiple: false,
        filters: [
          {
            text: "启用",
            value: 1,
          },
          {
            text: "停用",
            value: 0,
          },
        ],
        width: 50,
      },
      {
        title: "管理者",
        dataIndex: "owner",
        key: "owner",
        width: 100,
        render: (text) => (
          <span>{text && text.length > 0 ? text[0].name : "---"}</span>
        ),
      },
      {
        title: "创建时间",
        key: "timeCreate",
        dataIndex: "timeCreate",
        sorter: true,
        defaultSortOrder: "descend",
        width: 100,
        render: (text, record) =>
          moment(record.timeCreate).format("YYYY-MM-DD HH:mm:ss"),
      },
      {
        title: "操作",
        dataIndex: "operate",
        key: "operate",
        fixed: "right",
        width: 100,
        render: (text, record) => {
          const states = { operate: "mod", monitorId: record.monitorId };
          return (
            <span>
              <a onClick={() => this.changeStatus(record)}>
                {record.useStatus === "0" ? "启用" : "停用"}
              </a>
              <Divider type="vertical" />
              <Link
                to={`/messageCenter/supervisoryManager/supervisoryAdd?key=${JSON.stringify(
                  states
                )}`}
                disabled={record.useStatus === "1"}
              >
                编辑
              </Link>

              <Divider type="vertical" />

              <Popconfirm
                title="你是否要删除此监控?"
                onConfirm={() => this.deleteconfirm(record.monitorId)}
                onCancel={this.endcancel}
                okText="确定"
                cancelText="取消"
                placement="topRight"
              >
                <a disabled={record.useStatus === "1"}>删除</a>
              </Popconfirm>
            </span>
          );
        },
      },
    ];
    const keys = { operate: "add" };
    return (
      <div className={styles.root}>
        <div className={styles.topSearch}>
          <div style={{ display: "flex" }}>
            <Link
              to={`/messageCenter/supervisoryManager/supervisoryAdd?key=${JSON.stringify(keys)}`}
            >
              <Button type="primary" style={{ marginBottom: 17 }}>
                新增
              </Button>
            </Link>
          </div>
          <div style={{ color: "rgba(0,0,0,0.85)" }}>
            创建时间：
            <RangePicker
              showTime
              style={{ width: 334, marginLeft: 8, marginRight: 24 }}
              onChange={this.dateChange}
            />
            <Search
              placeholder="监控名称"
              style={{ width: 272 }}
              onSearch={this.handleSearch}
              allowClear
              onChange={this.clearChange}
            />
          </div>
        </div>
        <Table
          columns={columns}
          size="middle"
          dataSource={supervisoryList}
          loading={loading}
          locale={{ emptyText: "暂无数据！" }}
          scroll={supervisoryList.length===0?{x:false}:{ x: 1300 }}
          onChange={(e, filters, sorter) =>
            this.handleTableChange(e, filters, sorter)
          }
          rowKey="monitorId"
          pagination={{
            defaultPageSize: 10,
            showQuickJumper: true,
            showSizeChanger: true,
            current: pageNum,
            total: listTotal,
            showTotal: (total) => `共有 ${total} 条`,
          }}
        />
      </div>
    );
  }
}

export default SupervisoryManager;
